<template>
  <div class="app-container">
    <upload-excel-component :on-success="handleSuccess" :before-upload="beforeUpload" />
    <el-table :data="tableData" border highlight-current-row style="width: 100%;margin-top:20px;">
      <el-table-column v-for="item of tableHeader" :key="item" :prop="item" :label="item" />
    </el-table>
  </div>
</template>

<script>
import UploadExcelComponent from '@/components/UploadExcel/index.vue'
import { importEmployee } from '@/api/employees'
import { formatExcelDate } from '@/utils'
export default {
  name: 'UploadExcel',
  components: { UploadExcelComponent },
  data() {
    return {
      tableData: [],
      tableHeader: []
    }
  },
  methods: {
    // 本地文件上传之前的回调函数
    beforeUpload(file) {
      // 读取出来的数据的单位是bytes
      // 1Mb = 1024kb 1kb = 1024bytes 1个英文 1bytes
      const isLt1M = file.size / 1024 / 1024 < 1

      if (isLt1M) {
        return true
      }

      this.$message({
        message: 'Please do not upload files larger than 1m in size.',
        type: 'warning'
      })
      return false
    },
    // 本地文件上传成功的回调函数
    handleSuccess({ results, header }) {
      // 1.将excel中的数据读取出来转换js数据
      this.tableData = results
      this.tableHeader = header
      console.log('results', results)
      console.log('header', header)
      const data = this.dataFormat(results)
      console.log(data, 'data')
      this.doAdd(data)
    },
    // 格式化数据
    dataFormat(data) {
      // 1. 映射对象，根据映射对象找英文的键
      const mapInfo = {
        '入职日期': 'timeOfEntry',
        '手机号': 'mobile',
        '姓名': 'username',
        '转正日期': 'correctionTime',
        '工号': 'workNumber',
        '部门': 'departmentName',
        '聘用形式': 'formOfEmployment'
      }
      // 遍历data得到每一个对象
      const result = data.map(zhObj => {
        const enObj = {} // 放英文的值
        const zhkeys = Object.keys(zhObj)
        console.log('zhkeys', zhkeys) // ['入职日期', '姓名', '工号', '手机号', '转正日期', '部门']
        zhkeys.forEach(zhkey => {
          console.log('mapInfo[zhkey]', mapInfo[zhkey]) // 得到对应的英文键
          const enKey = mapInfo[zhkey]
          // 判定是否与时间相关
          if (enKey === 'timeOfEntry' || enKey === 'correctionTime') {
            enObj[enKey] = new Date(formatExcelDate(zhObj[zhkey]))
          } else {
            enObj[enKey] = zhObj[zhkey]
          }

          // console.log('enObj[mapInfo[zhkey]] = zhObj[zhkey]',enObj[mapInfo[zhkey]] = zhObj[zhkey])
        })
        return enObj
        //  console.log('enObj',enObj)
      })
      return result
    },
    async doAdd(data) {
      try {
        const res = await importEmployee(data)
        console.log('导入res', res)
        this.$message.success('导入成功')
        // 添加成功以后跳转回去
        this.$router.back()
      } catch (error) {
        console.log(error)
        this.$message.error('导入失败')
      }
    }
  }
}
</script>
